"""
@author: xiangping
@contact: xiangpingbu@gmail.com
@time: 2020/1/10 4:37 下午
@file: shaojie_controller
@Desc:
"""
from datetime import datetime
from typing import List
from app.services.business import lugang_biz_service
import logging

from flask import Blueprint, request, current_app
from app.controllers.response.response import SuccessResult
from app.exts import ironman_redis as redis
from app.utils import string_util, date_util

bp = Blueprint('lugang', __name__, url_prefix="/api/v1/lugang")
shaojie_bp = bp


@shaojie_bp.route('/data', methods=['GET'])
def test_dump_lugang_data():
    import random
    for tag, keys in lugang_biz_service.struct.items():
        for key in keys:
            redis.hset("lugang", key, random.randint(0, 340))
            redis.hset("lugang_update", key, datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S"))
            logging.info(key)

    return SuccessResult(detail="ok")


# 组分布,1-8代表8个组
mapping = {1: 1, 2: 3, 3: 5, 4: 7, 5: 8,
           6: 1, 7: 3, 8: 5, 9: 7, 10: 8,
           11: 1, 12: 3, 13: 5, 14: 6, 15: 7, 16: 8,
           17: 1, 18: 2, 19: 3, 20: 4, 21: 5, 22: 6, 23: 7,
           24: 1, 25: 2, 26: 3, 27: 4, 28: 5, 29: 6, 30: 7,
           31: 1, 32: 2, 33: 3, 34: 4, 35: 5, 36: 6, 37: 7,
           38: 1, 39: 2, 40: 3, 41: 4, 42: 5, 43: 6, 44: 7, 45: 8,
           46: 1, 47: 2, 48: 3, 49: 4,
           50: 1, 51: 2, 52: 3, 53: 4}

bad_points = [4, 5, 9, 10, 19, 21, 34, 35, 37, 40, 44]


@shaojie_bp.route('/temp', methods=['GET'])
def lugang_data():
    """
    炉缸区域温度
    :return:
    """
    time = request.args.get('time',date_util.dt_to_str(datetime.now(),"%Y-%m-%d %H:%M:%S"))

    time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
    value_dict = lugang_biz_service.get_data_by_time(time)

    # if string_util.is_not_empty(time):
    #     time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
    #     value_dict = lugang_biz_service.get_data_by_time(time)
    # else:
    #     value_dict = redis.hget_all_str_decode("lugang_hourly")

    group = []

    index = 0
    for tag, keys in lugang_biz_service.struct.items():
        # 高度标签s11700,s10200,s9200等
        item = dict(tag=tag.replace("s", ""))

        # 构造数据组,共有8组,0-45,45-90,90-135,135-180,280-225,225-270,270-315,3315-0
        for i in range(8):
            item['group' + str(i + 1)] = []

        for key in keys:
            index = index + 1
            # 通过索引获取组
            group_index = mapping[index]
            # 组装组名
            group_name = 'group' + str(group_index)

            if key not in value_dict.keys():
                logging.info("[炉缸区域温度]{},{}:{}不存在,使用默认值:0".format(tag, group_index, key))
            value = float(value_dict.get(key, 0))

            color = "red" if index in bad_points else "blue"
            item[group_name].append({"index": round(value, 2), "name": key, "color": color})

        group.append(item)

    return SuccessResult(detail=group)


@shaojie_bp.route('/historyCompare', methods=['GET'])
def history_compare():
    ind = request.args.get('ind')
    time = request.args.get('time')

    if time is not None:
        time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
    current, histories = lugang_biz_service.get_history(ind, time)

    return SuccessResult(detail=dict(current=current, histories=histories))


@shaojie_bp.route('/changeRate', methods=['GET'])
def change_rate():
    time = request.args.get('time')

    if time is not None:
        time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
    else:
        time = date_util.get_start_of_hour(datetime.now())

    group = lugang_biz_service.lugang_temp_change_rate(time)
    recommend = lugang_biz_service.lugang_temp_change_rate_recommend(time)

    return SuccessResult(detail=dict(group=group, recommend=recommend))
